package com.mutual.help.controller;


import com.mutual.help.entity.WxUsers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/sys")
public class uploadController {

    private String header = "http://localhost:8080";

    private String dirPath = "D:/fileupload/";

    // 简介图片地址
    private String simplePath = "";
    // 详细图片地址
    private StringBuilder detailsPath = new StringBuilder();

    @RequestMapping("/imgUpload")
    @ResponseBody
    public Map<String, Object> singleUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req,
                                            HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String filename = UUID.randomUUID() + suffixName;
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            //创建虚拟路径存储
            simplePath = "/images/"+ filename;
            map.put("image", simplePath);
            file.transferTo(new File(dirPath + filename));
            map.put("code", 0);
            map.put("msg", "上传成功");
        } catch (Exception e) {
            map.put("code", 1);
            map.put("msg", "上传失败");
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/videoUpload")
    @ResponseBody
    public Map<String, Object> videoUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req,
                                            HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String filename = UUID.randomUUID() + suffixName;
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            //创建虚拟路径存储
            simplePath = "/video/"+ filename;
            map.put("video", simplePath);
            file.transferTo(new File(dirPath + filename));
            map.put("code", 0);
            map.put("msg", "上传成功");
        } catch (Exception e) {
            map.put("code", 1);
            map.put("msg", "上传失败");
            e.printStackTrace();
        }
        return map;
    }

}
